/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.hiof.moraa.server.dao;

import com.hiof.moraa.mapping.TblAthlete;
import com.hiof.moraa.mapping.TblSupport;
import com.hiof.moraa.mapping.TblTeam;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 *
 * @author Bergy
 */
public class HibernateTeamDAOImp implements TeamDAO {

    private SessionFactory factory;

    public SessionFactory getFactory() {
        return factory;
    }

    public void setFactory(SessionFactory factory) {
        this.factory = factory;
    }

    @Override
    public TblTeam getTeamFromUserIdAndRouteID(int userId, int routeId) {
        Session session = factory.getCurrentSession();
        String hql = "from TblAthlete athlete where athlete.tblUser.id = :userId and athlete.tblRoute.id = :routeId";
        Query query = session.createQuery(hql);
        query.setInteger("userId", userId);
        query.setInteger("routeId", routeId);
        query.setMaxResults(1);
        TblAthlete athlete = (TblAthlete) query.uniqueResult();
        if (athlete != null) {
            return athlete.getTblTeam();
        } else {
            hql = "from TblSupport support where support.tblUser.id = :userId and support.tblRoute.id = :routeId";
            query = session.createQuery(hql);
            query.setInteger("userId", userId);
            query.setInteger("routeId", routeId);
            query.setMaxResults(1);
            TblSupport support = (TblSupport) query.uniqueResult();
            if (support != null) {
                return support.getTblTeam();
            }
        }
        return null;
    }

    @Override
    public TblTeam getTeamFromUsernameAndRouteID(String username, int routeId) {
        Session session = factory.getCurrentSession();
        String hql = "from TblAthlete athlete where athlete.tblUser.username = :username and athlete.tblRoute.id = :routeId";
        Query query = session.createQuery(hql);
        query.setString("username", username);
        query.setInteger("routeId", routeId);
        query.setMaxResults(1);
        TblAthlete athlete = (TblAthlete) query.uniqueResult();
        if (athlete != null) {
            return athlete.getTblTeam();
        } else {
            hql = "from TblSupport support where support.tblUser.username = :username and support.tblRoute.id = :routeId";
            query = session.createQuery(hql);
            query.setString("username", username);
            query.setInteger("routeId", routeId);
            query.setMaxResults(1);
            TblSupport support = (TblSupport) query.uniqueResult();
            if (support != null) {
                return support.getTblTeam();
            }
        }
        return null;
    }
}
